'''
Created on 18/gen/2010

@author: syn
'''
from elixir import session
from ui.GladeBase import GladeBase
from utils.Environment import logger
from data.models import Print
from ui import  generic_data_error
import gtk

NO_ENTITY = -1

class AddPrint(GladeBase):
    def __init__(self, product):
        logger.debug("UI: %s instance created" % self.__class__)
        GladeBase.__init__(self, 'add_print_dialog')
        self._init_gui_components()
        
        self.product = product
        
    def _init_gui_components(self):
        """
        Intialize gui components as needed. This is useful in the contructor or 
        binded with particular actions (for instance, a "clear" button, or "new" button) 
        """
        self.quantity_spinbutton.set_value(0)
    
    def _retrieve_components(self):
        """
        Retrieve all used gui components from builder. This method is called in the
        GladeBase constructor
        """
        self.get_from_builder('quantity_spinbutton')
    
    def _has_valid_data(self):
        """
        Formal control for data in the input form.
        @return: boolean. 'True' when data is valid
        """
        quantity = self.quantity_spinbutton.get_value_as_int()
        
        if not quantity:
            generic_data_error("Quantity must be greater than 0", self.quantity_spinbutton)
            return False
        
        return True
    
    def _save_data(self):
        """
        Save changes to db. 
        @return: 'True' if data have been successfully saved 
        """
        if not self._has_valid_data():
            return False
        
        # manage Print data object
        product_print = Print()
        
        product_print.product = self.product
        product_print.quantity = self.quantity_spinbutton.get_value_as_int()
        
        session.commit()
        
        return True
    
    # Signals
    def on_ok_button_clicked(self, object, data=None):
        if self._save_data():
            self.root_component.response(gtk.RESPONSE_OK)
    
    def run(self):
        return self.root_component.run()